package com.common.util;

import cn.hutool.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.lang.reflect.Type;


/**
 * json解析器
 */
public class JsonUtils {

	/**
	 * 解析对象到json字符串
	 * @param any
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String toJSONString(Object any) throws JsonProcessingException {
		String json = "{}";

		if (any == null) {
			return json;
		}

		ObjectMapper mapper = new ObjectMapper();

		try {
			json = mapper.writeValueAsString(any);
		}
		catch (JsonProcessingException e) {
			e.printStackTrace();
			// return json;
			throw e;
		}
		return json;
	}



	public static <T> T json2obj(String jsonStr, Type targetType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			JavaType javaType = TypeFactory.defaultInstance().constructType(targetType);

//			JSONObject jsonObject = new JSONObject(jsonStr);
//			var ResultData = jsonObject.getStr("data");

			return mapper.readValue(jsonStr, javaType);
		} catch (IOException e) {
			throw new IllegalArgumentException("将JSON转换为对象时发生错误:" + jsonStr, e);
		}
	}



}
